//create by lwy 2017年9月19日12:28:13

var selectLength;//所有商品
var selectLength2 = 0; //已选商品

function doAjax() {
    $.ajax({
        url: '/ShoppingCartC/getUserShoppingCart.json',
        dataType: 'json',
        data: {
            token: getItem('token'),
            // isSettlement:true,
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                $('.cart-box').empty();
                $('.mui-title').html('购物车(' + data.shoppingCartCount + ')');
                var cartData = data.datas;
                if (cartData.length > 0) {
                    for (var i = 0; i < cartData.length; i++) {
                        var shopSelectValue = '';
                        if(cartData[i].shopSelect){
                            shopSelectValue = '../img/selected.png';
                        }else{
                            shopSelectValue = '../img/select.png';
                        }
                        $('<div class="cart-detail-box mui-clearfix" id="cartBox' + cartData[i].shopId + '">' +
                            '<div class="cart-shopName" goodsNum="' + cartData[i].goods.length + '">' +
                            '<img class="shopSelect select" shopSelect="true" src="'+shopSelectValue+'"/><span>' + cartData[i].shopName + '</span></div>' +
                            '</div>').appendTo($('.cart-box'));
                        for (var j = 0; j < cartData[i].goods.length; j++) {
                            var payOnDelivery = '';
                            var allSelectValue = ''
                            if (cartData[i].goods[j].payOnDelivery == 0) { //不支持货到付款
                                payOnDelivery = ''
                            } else {
                                payOnDelivery = '<span class="payCash">货到付款</span>'; //支持货到付款
                            }
                            var hasSelect = '';
                            if(cartData[i].goods[j].shoppingCartStateValue == 1){ // 表示当前商品选中
                                hasSelect = '../img/selected.png';
                                allSelectValue = 'true';
                                selectLength2++;
                            }else if(cartData[i].goods[j].shoppingCartStateValue == 4){  //表示当前商品未选中
                                hasSelect = '../img/select.png';
                                allSelectValue = 'false';
                            }
                            var goodsMainImg = cartData[i].goods[j].goodsMainImage.split(',')[0];
                            $('<div class="mui-clearfix goods" cartId="' + cartData[i].goods[j].shoppingCartId + '" goodsId="' + cartData[i].goods[j].goodsId + '" specificationId="' + cartData[i].goods[j].specificationId + '" goodsImg="' + goodsMainImg + '" price="' + cartData[i].goods[j].memberPrice + '" inventory="' + cartData[i].goods[j].memberPrice + '">' +
                                '<div class="cart-select-box"><img class="goodsSelect select" cartId="' + cartData[i].goods[j].shoppingCartId + '" allselect="'+allSelectValue+'" src="'+hasSelect+'" price="' + cartData[i].goods[j].memberPrice + '" count="' + cartData[i].goods[j].count + '"/></div>' +
                                '<div class="cart-img-box"><img src="' + goodsMainImg + '"/></div>' +
                                '<div class="cart-product-box">' +
                                '<p class="goodsName">' + payOnDelivery + cartData[i].goods[j].goodsName + '</p>' +
                                '<span class="guige" count="'+cartData[i].goods[j].count+'" code="' + cartData[i].goods[j].code + '" inventory="' + cartData[i].goods[j].inventory + '" specificationId="' + cartData[i].goods[j].specificationId + '">' + cartData[i].goods[j].propertiesName + '</span>' +
                                '<span class="price">￥' + cartData[i].goods[j].memberPrice + '<i>×' + cartData[i].goods[j].count + '</i></span>' +
                                '</div>' +
                                '</div>').appendTo($('#cartBox' + cartData[i].shopId + ''))
                        }
                    }
                    selectLength = $('.goodsSelect').length;
                    if(selectLength2==selectLength){ //是否全选
                        $('.allSelect').attr('src','../img/selected.png');
                    }
                    $('.total-price-price').html('¥ ' + data.totalMoney);
                    $('#jiesuan').html('结算(' + selectLength2 + ')');
                }else{
                    $('<div class="kong"><img src="../img/kong.png" alt="暂无数据"></div>').appendTo($('.cart-box'));
                    $('.cart-total-price').hide();
                }
            }
            if(data.code==-1){
                window.location.href="login.html"
            }
            if(data.code==0){
                mui.toast(data.msg);
            }
        }
    })
}

doAjax();

//编辑
$('#edit').click(function () {
    $('#edit').hide();
    $('#complete').show();
    $('.total-price').hide();
    $('#jiesuan').hide();
    $('#delete').css('width','50%');
    $('#delete').show();
    $('.goodsName').each(function () {
        var myCount = $(this).siblings('.guige').attr('count');
        $(this).html('<span class="decrease">-</span><input type="text" value="'+myCount+'" class="editCount"><span class="add">+</span>')
    })
    //$('.goodsName').html('<span class="decrease">—</span><input type="text" value="1" class="editCount"><span class="add">+</span>');
    $('.price').hide();
    $('.cart-product-box').each(function () {
        var ifGuige = $(this).children('.guige').html();
        //console.log($(this).children('.guige').html())
        if (ifGuige == "" || ifGuige == undefined || ifGuige == null) {
        } else {
            $('<img src="../img/cart-choose.png"/>').appendTo($(this).children('.guige'))
        }
    })

    //点击购物车里的单个规格
    $('.guige').click(function () {
        $('.detail_box').empty();
        var guigeThis = $(this);
        var goodsId = $(this).parent().parent().attr('goodsId');
        var goodsImg = $(this).parent().parent().attr('goodsImg');
        var specificationId = $(this).parent().parent().attr('specificationId');
        var goodsPrice = $(this).parent().parent().attr('price');
        var goodsCount = $(this).attr('count');
        inventory = $(this).attr('inventory');
        $('.specification_img img').attr('src', goodsImg);
        $('.spePrice').html('¥ ' + goodsPrice);
        $('.inventory').html('库存' + inventory + '件');
        $('.code').html('商品编号：'+$(this).attr('code'));
        //console.log(specificationId);
        var speWidth = $('.specification_img').width() / 100;
        var BodyWidth = $('body').width() * speWidth;
        $('.specification_img').css('height', '' + BodyWidth + 'px');
        $.ajax({
            url: '/specificationC/getSpecification.json',
            dataType: 'json',
            data: {
                goodid: goodsId,
            },
            type: 'post',
            success: function (data) {
                var speData = data.datas;
                //规格
                for (var i = 0; i < speData.length; i++) {
                    $('<div class="detail_small_box" id="detail_spe' + speData[i].id + '"></div>').appendTo($('.detail_box'));
                    $('<div class="detail_title">' + speData[i].name + '</div>').appendTo($('#detail_spe' + speData[i].id + ''));
                    $('<div class="detail_spe mui-clearfix" id="detailOne_spe' + speData[i].id + '"></div>').appendTo($('#detail_spe' + speData[i].id + ''));
                    for (var b = 0; b < speData[i].data.length; b++) {
                        $('<div class="spe-one" parent="' + speData[i].id + '" son="' + speData[i].data[b].id + '" id="' + speData[i].data[b].id + '">' + speData[i].data[b].content + '</div>').appendTo($('#detailOne_spe' + speData[i].id + ''));
                    }
                }
                //数量
                $('<div class="detail_count_title">' +
                    '<span>数量</span>' +
                    '<span class="choose_count">' +
                    '<span class="decreace" id="decreace">-</span' +
                    '><input id="count" type="text" class="count" value="'+goodsCount+'"' +
                    '><span class="add" id="add">+</span>' +
                    '</span>' +
                    '</div>').appendTo($('.detail_box'));

            }
        })
        $('.specification_box').show();
        $('body,.mui-content').css({'height':'100%','overflow':'hidden'});

        //点击获取规格图片库存等信息
        $('body').on('click', '.spe-one', function () {
            $(this).addClass('spe_act');
            $(this).attr('ifAct', 'true');
            $(this).siblings().attr('ifAct', 'false');
            $(this).siblings().removeClass('spe_act');
            speB_Id = $(this).attr('parent');
            var o = $("div[ifAct='true']");
            param = '';
            for (var i = 0; i < o.length; i++) {
                param += $(o.get(i)).attr('parent') + ':' + $(o.get(i)).attr('son');
                if (i != o.length - 1) {
                    param += ','
                }
            }

            $.ajax({
                url: '/goodSpecificationC/getGoodSpecification.json',
                dataType: 'json',
                data: {
                    goodid: GetQueryString('goodsId'),
                    propertiesid: param,
                },
                type: 'post',
                success: function (data) {
                    //获取规格库存，图片
                    if (data.code == 1) {
                        $('#spe_img').attr('src', data.datas.image);
                        $('.price').html('¥' + data.datas.memberPrice);
                        $('.inventory').html('库存' + data.datas.inventory + '件');
                        inventory = data.datas.inventory;
                        propertiesId = data.datas.id;
                        propertiesName = data.datas.propertiesName;
                    }
                }
            })
        })

        //点击确定
        $('.spe_certain').click(function () {
            //获取已选择字符串拼接
            var speStr = '';
            $('.spe_act').each(function () {
                speStr += $(this).html() + ', ';
            })
            speStr += '* ' + $('.count').val();
            guigeThis.html(propertiesName + '<img src="../img/cart-choose.png">');
            guigeThis.attr('specificationId', propertiesId);
            $('body,.mui-content').css({'height':'auto','overflow':'auto'});
            $('.specification_box').hide();
        })
    })
})

//关闭
$('.colse_spe').click(function () {
    $('.specification_box').hide();
    $('body,.mui-content').css({'height':'auto','overflow':'auto'});
    $('#goodsBox').show();
})

//完成
$('#complete').click(function () {
    var modifydata = '';
    $('.goods').each(function () {
        var editCartId = $(this).attr('cartId') + ':';
        var editCount = $(this).children().find('input').val() + ':';
        var speId = $(this).children().find('.guige').attr('specificationid');
        modifydata += editCartId + editCount + speId + ',';
    })
    $.ajax({
        url: '/ShoppingCartC/modifyUserShoppingCart.json',
        dataType: 'json',
        data: {
            token: getItem('token'),
            modifydata: modifydata,
        },
        success: function (data) {
            if (data.code == 1) {
                doAjax();
                $('#complete').hide();
                $('#edit').show();
                $('.total-price').show();
                $('#delete').hide();
                $('#jiesuan').show();
                var hasSelect2 = $(".goodsSelect[allSelect='true']").length;
                selectLength2 = hasSelect2;
                $('#jiesuan').html('结算(' + hasSelect2 + ')');
            }
        }
    })
})


//选择
$('body').on('click', '.select', function () {
    var selThis = $(this);
    var ifSelect = $(this).attr('src');
    var shopSelect = '';
    var ifSelectValue = ''; //代表传入参数option
    var cartId = '';//代表传入参数cartID
    if(ifSelect=='../img/selected.png'){
        ifSelectValue = false; //当前为选中，点击应变为未选中,所以传入参数为false
    }else{
        ifSelectValue = true; //当前未选中，点击应变为选中,所以传入参数为true
    }
    if($(this).attr('shopSelect')){ //当前为店铺
        shopSelect = 'true';
        var shopGoods = selThis.parent().siblings().children().find('.goodsSelect');
        for(var i=0;i<shopGoods.length;i++){
            cartId+=$(shopGoods[i]).attr('cartid')+',';
        }
    }else{ //当前为商品
        shopSelect = 'false';
        cartId = selThis.attr('cartid');
    }

    $.ajax({
        url:'/ShoppingCartC/optionCart.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            id:cartId,
            option:ifSelectValue
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                if(selThis.attr('src')=='../img/select.png'){ //当前为未选中，变为已选
                    if(selThis.attr('shopSelect')){ //如果为商铺勾选
                        selThis.attr('src','../img/selected.png');
                        selThis.parent().siblings().children().find('.goodsSelect').attr({'src':'../img/selected.png','allSelect':'true'});
                        var shopGoods2 = selThis.parent().siblings().children().find('.goodsSelect').length;
                        selectLength2 = selectLength2+shopGoods2;
                        console.log(shopGoods2);
                        console.log(selectLength2);
                    }else{
                        selThis.attr({'src':'../img/selected.png','allSelect':'true'});
                        selectLength2++;
                        var parentLength = selThis.parent().parent().siblings('.cart-shopName').attr('goodsnum');
                        var thisGoodsSelect = selThis.parent().parent().siblings().children().find(".goodsSelect[allSelect='true']").length;
                        if((thisGoodsSelect+1)==parentLength){
                            selThis.parent().parent().siblings('.cart-shopName').find('img').attr({'src':'../img/selected.png'});
                        }
                        console.log(parentLength);
                        console.log(thisGoodsSelect);
                        console.log(selectLength2);
                    }

                }else{  //当前为已选，变为未选
                    if(selThis.attr('shopSelect')){  //如果为商铺勾选
                        selThis.attr('src','../img/select.png')
                        selThis.parent().siblings().children().find('.goodsSelect').attr({'src':'../img/select.png','allSelect':'false'});
                        var shopGoods3 = selThis.parent().siblings().children().find('.goodsSelect').length;
                        selectLength2 = selectLength2-shopGoods3;
                        console.log(shopGoods3);
                        console.log(selectLength2);
                    }else{
                        selThis.attr({'src':'../img/select.png','allSelect':'false'});
                        selectLength2--;
                        var parentLength2 = selThis.parent().parent().siblings('.cart-shopName').attr('goodsnum');
                        var thisGoodsSelect2 = selThis.parent().parent().siblings().children().find(".goodsSelect[allSelect='true']").length;
                        console.log(parentLength2);
                        console.log(thisGoodsSelect2);
                        console.log(selectLength2);
                        if(thisGoodsSelect2<parentLength2){
                            selThis.parent().parent().siblings('.cart-shopName').find('img').attr({'src':'../img/select.png'});
                        }
                    }

                    $('.allSelect').attr('src','../img/select.png');
                }
                ifAll();
                getTotalPrice();
                var hasSelect = $(".goodsSelect[allSelect='true']").length;
                $('#jiesuan').html('结算(' + hasSelect + ')');
            }
        }
    })
})


function ifAll() {
    if(selectLength2==selectLength){ //是否全选
        $('.allSelect').attr('src','../img/selected.png');
    }
}

//全选
$('.allSelect').click(function () {
    var option2;
    var cartId2 = '';
    var selThis2 = $(this);
    $(".goodsSelect").each(function () {
        cartId2+=$(this).attr('cartid')+',';
    })
    if ($(this).attr('src') == '../img/select.png') {
        option2 = 'true';
    }else{
        option2 = 'false';
    }
    $.ajax({
        url:'/ShoppingCartC/optionCart.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            id:cartId2,
            option:option2
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                if (selThis2.attr('src') == '../img/select.png') {
                    selThis2.attr('src', '../img/selected.png');
                    $('.select').attr('src', '../img/selected.png');
                    $('.goodsSelect').attr('allSelect', 'true');
                    selectLength2 = selectLength;
                } else {
                    selThis2.attr('src', '../img/select.png');
                    $('.select').attr('src', '../img/select.png');
                    $('.goodsSelect').attr('allSelect', 'false');
                    selectLength2 = 0;
                }
                getTotalPrice();
                $('#jiesuan').html('结算(' + selectLength2 + ')');
            }
        }
    })
})

//计算价格
function getTotalPrice() {
    var price = 0;
    $(".goodsSelect[allSelect='true']").each(function () {
        var unitPrice = $(this).attr('count') * $(this).attr('price');
        price += unitPrice;
    })

    $('.total-price-price').html('¥ ' + (price).toFixed(2));
}

getTotalPrice();

//删除
$('#delete').click(function () {
    var delId ='';
    $(".goodsSelect[allSelect='true']").each(function () {
        delId+=$(this).attr('cartId')+',';
    })
    $.ajax({
        url:'/ShoppingCartC/deleteUserShoppingCart.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            id:delId,
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                $('#complete').hide();
                $('#edit').show();
                $('.total-price').show();
                $('#delete').hide();
                $('#jiesuan').show();
                var hasSelect3 = $(".goodsSelect[allSelect='true']").length;
                $('#jiesuan').html('结算(' + hasSelect3 + ')');
                doAjax();
                $('.total-price-price').html('¥ 0.00');
            }
        }
    })
})

$(document).ready(function () {
    //添加
    $("body").on('click','.add',function(){
        var count = $(this).parent().find('input').val();
        var inventory = $(this).parent().siblings('.guige').attr('inventory');
        count++;
        if(count>inventory){
            mui.toast('加入购物车数量不能超过总库存');
            count=inventory;
        }
        $(this).parent().find('input').val(count);
    })
    //减少
    $("body").on('click','.decrease',function(){
        var count2 = $(this).parent().find('input').val();
        count2--;
        if(count2<1){
            count2=1;
        }
        $(this).parent().find('input').val(count2);
    })
    //输入产品数量
    $("body").on('change','.editCount',function(){
        var inventory3 = $(this).parent().siblings('.guige').attr('inventory');
        //判断输入数量是否为空或小于1
        if($(this).val()==""||$(this).val()==NaN||$('this').val()<1||$('this').val()==null||$('this').val()==undefined){
            $(this).val('1');
        }
        if($(this).val()>inventory3){
            mui.toast('加入购物车数量不能超过总库存');
            $(this).val(inventory3);
        }
    })
})

$(document).ready(function () {
    //添加
    $("body").on('click','#add',function(){
        var count = $(this).parent().find('input').val();
        count++;
        if(count>inventory){
            mui.toast('加入购物车数量不能超过总库存');
            count=inventory;
        }
        $(this).parent().find('input').val(count);
    })
    //减少
    $("body").on('click','#decreace',function(){
        var count2 = $(this).parent().find('input').val();
        count2--;
        if(count2<1){
            count2=1;
        }
        $(this).parent().find('input').val(count2);
    })
    //输入产品数量
    $("body").on('change','#count',function(){
        //判断输入数量是否为空或小于1
        if($(this).val()==""||$(this).val()==NaN||$('this').val()<1||$('this').val()==null||$('this').val()==undefined){
            $(this).val('1');
        }
        if($(this).val()>inventory){
            mui.toast('加入购物车数量不能超过总库存');
            $(this).val(inventory);
        }
    })
})

//结算
$('#jiesuan').click(function () {
    var carStr = '';
    $(".goodsSelect[allSelect='true']").each(function () {
        var goodsId = $(this).parent().parent().attr('goodsid')+':';
        var goodsNum = $(this).attr('count')+':';
        var specificationid = $(this).parent().parent().attr('specificationid')+',';
        carStr+=goodsId+goodsNum+specificationid;
    })
    console.log(carStr);
    $.ajax({
        url:'/zuoDanC/confirmOrder.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            carStr:carStr,
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                window.location.href="confirmOrder.html?totalMoney="+data.datas.totalMoney+"&ifCart=true";
            }
        }
    })
})